import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

@Injectable()
export class LoginService {
  constructor(private http: HttpClient) {
  }

  private url = '/api/login';

  private headers = new HttpHeaders({'Content-Type': 'application/json'});

  onLogin(username: string, password: string): Promise<any> {
    const body = {
      username: username,
      password: password
    };

    return this.http.post(this.url, body, {headers: this.headers}).toPromise();
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  logout() {
    localStorage.removeItem('username');
  }

  isLogged() {
    return localStorage.getItem('username') !== null;
  }
}

export const LOGIN_PROVIDERS: Array<any> = [
  {provide: LoginService, useClass: LoginService}
];
